<?php
namespace common\components;

use yii\helpers\ArrayHelper;
use yii\web\Controller;
use Yii;

/**
 * 整个web项目基类控制器
 * @author Administrator
 *
 */
class BaseWebController extends Controller
{
	/**
	 * 响应成功标识
	 * 用于平台响应统一ajax操作状态 与 getResponseArrForAjax一起使用
	 * @var integer
	 */
	const RESPONSE_SUCCESS = 1;
	
	/**
	 * 响应失败标识
	 * @var integer
	 */
	const RESPONSE_FAILURE = 0;

	const RESPONSE_DATA_URL = '_url';

    /**
     * csrf验证
     * @var bool
     */
    public $enableCsrfValidation = true;

    public function setTitle($title = "")
    {
    	empty($title) && $title = @Yii::$app->params['sys_title'];
    	
        $this->getView()->title = $title;
    }

    /**
     * 获取post
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function post($key = null, $default = null) 
    {
        return Yii::$app->request->post($key, $default);
    }

    /**
     * 获取get
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function get($key = null, $default = null) {
        return Yii::$app->request->get($key, $default);
    }

    /**
     * 获取get 和 body参数
     * @param null $key
     * @param null $default
     * @return array|mixed
     */
    public function requestAll($key = null, $default = null)
    {
        $requestParams = array_merge(\Yii::$app->getRequest()->getBodyParams(), $this->get());

        if ( $key === null ) {
            return $requestParams;
        }
        return ArrayHelper::getValue($requestParams, $key, $default);
    }

    protected function setCookie($name, $value, $expire = 0)
    {
        $cookies = Yii::$app->response->cookies;

        $domain = isset(\Yii::$app->params['domain']) ? \Yii::$app->params['domain'] : "";

        $cookies->add(new \yii\web\Cookie([
            'name' => $name,
            'value' => $value,
            'expire' => $expire ? ( time() + $expire ) : $expire,
            'domain' => $domain
        ]));
    }

    protected  function getCookie($name, $default_val='')
    {
        $cookies = Yii::$app->request->cookies;

        return $cookies->getValue($name, $default_val);
    }


    protected function removeCookie($name)
    {
        $cookies = Yii::$app->response->cookies;

        $cookies->remove($name);
    }

    protected function isAjax()
    {
        return Yii::$app->request->isAjax;
    }

   public function jsonResponse($status, $msg = null, array $data = [])
   {
       if ( $msg === null ) {
           if ( $status == self::RESPONSE_SUCCESS ) {
                $msg = "操作成功";
           } else {
               $msg = "操作失败";
           }
       }
       $response = \Yii::$app->response;
       $response->format = $response::FORMAT_JSON;
       $response->data = [
           'status'=>$status,
           'message'=>$msg,
           'data'=>$data
       ];
       return $response;
   }
}


